package fr.cephb.servlet;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Just for fun: a servlet printing a label as PNG
 * parameters: text; width; heigh;
 * @author lindenb
 *
 */
public class DymoServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException
	{
	final String fontName="Sketch Rockwell";
	String text=req.getParameter("text");
	if(text==null) text="";
	String wstr=req.getParameter("width");
	String hstr=req.getParameter("height");
	Dimension dim= new Dimension(
		wstr!=null?Integer.parseInt(wstr):640,
		hstr!=null?Integer.parseInt(hstr):400
		);
	
	BufferedImage img= new BufferedImage(dim.width,dim.height,BufferedImage.TYPE_INT_ARGB);
	Graphics2D g= img.createGraphics();
	short fsize=4;
	Font bestfont=null;
	Rectangle2D bestrect=null;
	while(true)
		{
	
		Font f=new Font(fontName,Font.PLAIN,fsize);
		
		g.setFont(f);
		FontRenderContext frc = g.getFontRenderContext();
		Rectangle2D r= f.getStringBounds(text, frc);
		if(bestfont==null)
			{
			bestrect=r;
			bestfont=f;
			}
		
		if(r.getHeight() >= dim.height ) break;
		if(r.getWidth() >= dim.width ) break;
		bestfont=f;
		bestrect=r;
		fsize+=5;
		}
	
	g.setFont(bestfont);
	g.setColor(Color.BLACK);
	g.drawString(text,
		(int)((dim.width-bestrect.getWidth())/2.0),
		(int)(bestrect.getHeight()+(dim.height-bestrect.getHeight())/2.0)
		);
	g.dispose();
	res.setContentType("image/png");
	OutputStream out=res.getOutputStream();
	ImageIO.write(img, "png",out);
	out.flush();
	out.close();
	}
}
